#-*- coding: utf-8 -*-

#This file is part of pyLot library.
#
# pyLot is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pyLot is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pyLot.  If not, see <http://www.gnu.org/licenses/>.

__author__ = u'Pierre Puiseux, Guillaume Baty'
__copyright__ = u"Copyright 2011-2012 (C) andheo, Université de Pau et des Pays de l'Adour"
__credits__ = [u'Pierre Puiseux', u'Guillaume Baty']
__license__ = "GNU Lesser General Public License"

__all__ = ['BaseHandler']

import gettext

from traits.api import implements

from ..interfaces.i_handler import IHandler

from _pylot.minimal.container import Container
from _pylot.minimal.datum import Datum
from _pylot.minimal.system import LANG, ENCODING
from _pylot.data import regexpr
from _pylot.data.regexpr import match
from _pylot.defaultconf import TRANSLATORS, install_translator

def set_texts(obj_text_list, field=u'text'):
  if field == u'text':
    for obj, text in obj_text_list :
      if isinstance(obj, (Datum, Container)) :
        obj.alias = text
      else :
        pass
  elif field == u'tooltip':
    for obj, text in obj_text_list :
      if isinstance(obj, (Datum, Container)):
        obj.tooltip = text
      else :
        pass

class BaseHandler():

  implements(IHandler)
  mo_file_dir = None
  level = u'user'

  def setCurrentLocale(self, locale):
    self._current_locale = locale

  current_locale = property(lambda self:self._current_locale, setCurrentLocale)


  def __init__(self):

    self.__translators = {}
    self._handlers = []
    self._current_locale = 'en'

    if self.mo_file_dir and self.mo_file_dir.isdir():
      for path in self.mo_file_dir.listdir() :
        if path.isdir() and match(regexpr.co_i18n_locale, str(path.name)) :
          locale = path.name
          try :
            self.__translators[locale] = gettext.translation(self.identifier,
              self.mo_file_dir.encode(ENCODING),
              languages=[locale.encode(ENCODING)])
          except IOError:
            pass

    else :
      self.__translators = TRANSLATORS


  def translate(self, locale=None, force=False, recursive=True):
    u"""
    Translates dynamically the handler.
    Locale is an unicode string composed of two parts separated by '_'.
    The first part is the lang, the second the country.
    
    For example, British English is defined by u'en_GB'.
    French from France: u'fr_FR'

    .. seealso ::
      
      pylot howto for i18n
  
    :param locale: the new locale (ex: u'fr_FR')
    :type locale: :obj:`unicode`
    """
    # install translator local to plugin (can be accessed using tr_ method)
    if locale is None :
      locale = LANG
    if locale == self.__current_locale and force is False:
      return
    self.__current_locale = locale

    # install global translator in builtin namespace 
    #(can be accessed using _ function)
    install_translator(locale)

    try :
      self._tr = self.__translators[locale].ugettext
    except KeyError :
      pass

    if recursive is True :
      for child in self:
        child.translate(locale, force, recursive)

    # retranslate handler
    self._translate()

  def tr_(self, src, disambiguation=None, n=None):
    u"""
    Returns a translated version of src, optionally based on a disambiguation 
    string and value of n for strings containing plurals
    Otherwise returns src itself if no appropriate translated string is available.

    This method is similar to default gettext "_" method.
    the parameter must be an **unicode** string. The translation is also an
    unicode string. If no translations available, original unicode string is 
    returned.

    This method is also recognized by plugin_editor and i18n tools, so all
    these string are extracted and store in plugin i18n/msg.pot file

    .. seealso ::

      Program used for translation : `Babel <http://babel.edgewall.org/>`_
      Original builtin i18n library : `Python gettext <http://docs.python.org/library/gettext.html>`_
      Official `Unicode Howto <http://docs.python.org/howto/unicode.html>`_

    """
    return self._tr(src)

  def _tr(self, txt):
    u"""
    Private method only used if i18n fails. 
    Please NEVER use this method.
    You MUST use :meth:`~_pylot.interfaces.handler.tr_`
    """
    return txt

  def _translate(self):
    pass

  def switchUserLevel(self, level=u'user', force=False, recursive=True):
    pass

  def writeSettings(self, userconf_dir, recursive=True):
    pass

  def readSettings(self, userconf_dir, recursive=True):
    pass

  def append(self, child):
    self._handlers.append(child)

  def init(self):
    pass

  def close(self):
    pass

  def __iter__(self):
    for handler in self._handlers :
      yield handler

